package com.itic.mobile.base;



import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;

import com.itic.appbase.applications.files.utils.FileHelper;
import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.applications.sys.region.service.RegionService;
import com.itic.appbase.applications.sys.sysexception.persistence.model.SysException;
import com.itic.appbase.applications.sys.sysexception.service.SysExceptionService;
import com.itic.appbase.applications.sys.syssetting.service.SysSettingService;
import com.itic.appbase.applications.sys.token.service.TokenService;
import com.itic.appbase.applications.sys.user.persistence.model.SysUser;
import com.itic.appbase.applications.sys.user.service.SysUserService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.type.DefaultSysSettingKeyValue;
import com.itic.appbase.framework.utils.CalendarHelper;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.HttpRequestUtils;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.PropertyGetter;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.system.market.product.persistence.model.Product;
import com.itic.system.market.product.persistence.model.ProductExample;
import com.itic.system.market.product.persistence.model.ProductExample.Criteria;
import com.itic.system.market.product.service.ProductService;

public class BaseMobile
     extends BaseController {
	protected static String Url = "http://120.55.205.5/webservice/sms.php?method=Submit";//发送短信的URL
	protected static String kplUrl = "https://coupon.m.jd.com/union?mtm_source=kepler-m&mtm_subsource=2d67b6f7d09e42c28d49fa88248db03c&mopenbp5=";
	
	@Autowired
	protected OutCommonService outCommonService;

	@Autowired
    protected SysSettingService sysSettingService;
	
	@Autowired
    protected SysExceptionService sysExceptionService;
	
	@Autowired
	protected RegionService regionService;

	@Autowired
	protected TokenService tokenService;
	
	@Autowired
	protected SysUserService sysUserService;
	
	@Autowired
	protected ProductService productService;
	 
	//商品过滤字段
    protected static String[] ignoreProperties = new String[] { "createUser", "isEffective", "updateTime", "note","createTime", "orgCode", "reorder" };
  	
	
	protected static final String RequestUser = "RequestUser";
	
	protected static final String ORG_CODE = "00021287828";
	protected static final String CREATE_USER = "0";
	
	//接口返回键
    protected static final String RESULT = "result";
    protected static final String DATA = "data";
    protected static final String CODE = "code";
    protected static final String MSG = "msg";
    protected static final String IS_STORE = "isStore";
    
    //接口返回值
    protected static final String SUCCESS = "success";
    protected static final String FAIL = "fail";
    protected static final String LOGIN = "login";
    
    //通用错误信息
    protected static final String SUCCESS_ERROR_CODE = "10000";//请求成功
    protected static final String SUCCESS_ERROR_MSG = "请求成功！";//服务器异常
    
    protected static final String LOGIN_ERROR_CODE = "10001";//用户未登入或者TOKEN无效
    protected static final String LOGIN_ERROR_MSG = "登入过期，请重新登入！";//用户未登入
    
    protected static final String PARAM_ERROR_CODE = "10002";//缺少必填参数
    protected static final String PARAM_ERROR_MSG = "缺少必填参数，请检查！";//参数不正确
    
    protected static final String SERVER_ERROR_CODE = "10003";//服务器异常
    protected static final String SERVER_ERROR_MSG = "服务器开小差啦！";//服务器异常
    
    //业务错误信息
    protected static final String PHONE_CODE_ERROR_CODE = "10004";//验证码无效
    protected static final String PHONE_CODE_ERROR_MSG = "验证码无效！";//验证码无效
    
    protected static final String PHONE_CODE_SEND_ERROR_CODE = "10004";//验证码无效
    protected static final String PHONE_CODE_SEND_ERROR_MSG = "验证码发送失败，请重试！";//验证码无效
    
    protected static final String PWD_ERROR_CODE = "10005";//用户名或密码无效
    protected static final String PWD_ERROR_MSG = "用户名或密码不正确";//验证码无效
    
    protected static final String TOKEN_ERROR_CODE = "10006";//token无效
    protected static final String TOKEN_ERROR_MSG = "登入授权码失效!";//验证码无效   

    protected static final String PHONE_REGED_ERROR_CODE = "10007";//token无效
    protected static final String PHONE_REGED_ERROR_MSG = "手机号已注册，请更换!";//验证码无效
    
    protected static final String PRODUCT_EMPTY_ERROR_CODE = "10008";//token无效
    protected static final String PRODUCT_EMPTY_ERROR_MSG = "商品已下架!";//验证码无效
    
    protected static final String MSG_NULL_ERROR_CODE = "10009";//token无效
    protected static final String MSG_NULL_ERROR_MSG = "消息未找到!";//验证码无效
    
    protected static final String LESS_MONEY_ERROR_CODE = "10010";
    protected static final String LESS_MONEY_ERROR_MSG = "金额不足!";//
    
    protected static final String ACCOUNT_ID_ERROR_CODE = "10011";
    protected static final String ACCOUNT_ID_ERROR_MSG = "提现账号未找到，请重新填写!";//
    
    protected static final String VIP_TYPE_ERROR_CODE = "10012";
    protected static final String VIP_TYPE_ERROR_MSG = "VIP类型不正确!";//
    
    protected static final String PRODUCT_ITEM_ID_ERROR_CODE = "10013";
    protected static final String PRODUCT_ITEM_ID_ERROR_MSG = "商品项不正确！";//
    
    protected static final String WX_PAY_NOT_SUCCESS_CODE = "10014";
    protected static final String WX_PAY_NOT_SUCCESS_MSG = "微信支付调用失败！";//
    
    protected static final String OPENID_ERROR_CODE = "10015";
    protected static final String OPENID_ERROR_MSG = "微信支付需要先获得OPENID！";//
    
    protected static final String CODE_ERROR_CODE = "10016";
    protected static final String CODE_ERROR_MSG = "微信CODE码与小程序APPID不匹配，请检查！";//
    
    protected static final String PRODUCT_ITEM_ERROR_CODE = "10017";
    protected static final String PRODUCT_ITEM_ERROR_MSG = "剧集项未找到，请检查！";//
    
    protected static final String SEND_CODE_ERROR_CODE = "10018";
    protected static final String SEND_CODE_ERROR_MSG = "验证码发送失败，请联系管理员！";//
    

    protected static final String FILE_SUFFIX_ERROR_CODE = "10008";//token无效
    protected static final String FILE_SUFFIX_ERROR_MSG = "文件名称没有后缀，请补全文件名后缀!";//验证码无效  
    
    
    protected static final String NOT_FILE_ERROR_CODE = "10009";//token无效
    protected static final String NOT_FILE_ERROR_MSG = "非文件上传!";//验证码无效 
    /**
     * 异常日志
     * @param e
     */
    public void logException( String className, String methodName, String message, String desc, Exception e ){
    	try{  
    	   Date now = new Date();
		   String nowString = DateHelper.formatDateTime(now);
		   
		   SysException exception = new SysException();
		   exception.setId(IdGen.uuid());
		   exception.setExceptionClass(className);
		   exception.setExceptionMethod(methodName);
		   
		   //exception.setExceptionNote();
		   exception.setExceptionNote(desc);
		   
		   exception.setExceptionTime(nowString);
		   
		   exception.setExceptionMessage(message);
		   
		   StringBuffer bf = new StringBuffer();
		   bf.append(FileHelper.getRootDir());
		   bf.append("exception");
		   bf.append(File.separator);
		   bf.append(DateHelper.getDateStringByDate(new Date(), "yyyy-MM-dd"));
		   bf.append(File.separator);
		   String filePath = bf.toString();
		   File f=new File(filePath);
		   if(!f.exists()){
		    	 f.mkdirs();
		   }
		   bf.append(IdGen.uuid());
           bf.append(".txt");
           filePath = bf.toString();
		   File tempfile =new File(filePath);
		   if(!tempfile.exists()){
		    	tempfile.createNewFile();
		   }
         
		   //输出一个错误日志文件
		   FileOutputStream out = new FileOutputStream(filePath);//确认流的输出文件和编码格式，此过程创建了“test.txt”实例
			
		   PrintStream printStream = new PrintStream(out);
		   e.printStackTrace(printStream);
		   out.close();
		   String replace = filePath.replace(FileHelper.getRootDir(), "");
		   //保存全路径
		   exception.setExceptionFilepath(PropertyGetter.getString("app.download.path") +"mall_fileupload/"+ replace);
		   sysExceptionService.add(exception);
		   
    	}catch(Exception temp){
		   temp.printStackTrace();
	    }
    }
    
    /**
     * 获得用户信息
     * @param request
     * @return
     */
    public SysUser getRequestUser(HttpServletRequest request) {
    	Object user = request.getAttribute(RequestUser);
    	if(user!=null && user instanceof SysUser)
    		return (SysUser) user;
    	else
    		return null;
    }


    
    /**
     * 判断是否还有更多
     * @param request
     * @param count
     * @return
     */
    protected String isMore( HttpServletRequest request,int count){
    	String result = "have";
    	
    	String recordNow = this.getCleanParams(request, IticConst.RECORD_NOW);
        String pageSize = this.getCleanParams(request, IticConst.PAGE_SIZE);
        
        if( StringHelper.isEmpty(recordNow) ){
        	recordNow = "0";
        }
        
        if( StringHelper.isEmpty(pageSize) ){
        	pageSize = "10";
        }
        
        String addString = NumberStringHelper.addString(recordNow, "1");
        String mulString = NumberStringHelper.mulString(addString, pageSize);
        
        if( !NumberStringHelper.isGreaterNoEqual(count+"", mulString) ){
        	result = "none";
        }
        return result;
    }
    /**
     * 是否跨域方法
     * @param response
     * @return
     */
    public HttpServletResponse isCrrossDomain( HttpServletResponse response ){
    	//是否允许跨域
    	String isCrrossDomain = sysSettingService.getByKey("IS_CRROSS_DOMAIN");
    	String isSetCrrossDomain = PropertyGetter.getString("app.is.crross.domain");
    	if( isSetCrrossDomain.equals( isCrrossDomain ) ){
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
            response.setHeader("Access-Control-Allow-Credentials", "true");
    	}
    	return response;
    }
    
    /**
     * 获取 验证码的过期 时间
     * @param date
     * @return
     */
    public Date getExpiredTimeCode(Date date){
    	String minuteStr = "5";//默认CODE有效期为5分
    	String minuteSet =sysSettingService.getByKey("CODE_EXPIRED_MINUTE");
    	if( StringHelper.isNotBlank(minuteSet) ){
    		minuteStr = minuteSet;
    	}
    	Date dateAfter = CalendarHelper.getMinuteAfter(date, Integer.parseInt(minuteStr));
    	return dateAfter;
    }
    
    /**
     * 用户默认的头像地址
     * @return
     */
    public String getDefaultHeadImg(){
    	String defaultValue = DefaultSysSettingKeyValue.defaultHeadImg.getValue();
		String sysValue = sysSettingService.getByKey(DefaultSysSettingKeyValue.defaultHeadImg.getKey());
		if( StringHelper.isNotBlank(sysValue) ){
			defaultValue = sysValue;
		}
		return defaultValue;
    }
    
    /**
     * 辰希公司发送验证码
     * @return
     */
    public String sendMassageCx(String phone,String codeCont){
    	String result = FAIL;
    	String msg = "【友惠家】您的验证码是："+codeCont+"，3分钟有效时间，请不要把验证码泄露给其他人。";
		try {
			String xmString = new String(msg.getBytes("UTF-8"));
			msg = URLEncoder.encode(xmString, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String httpGet = HttpRequestUtils
				.httpGet("http://47.93.44.166/SMS/smsSender?name=youhui&pwd=Y39dkGW249&phone="+phone+"&msg="+msg);
		if(httpGet.contains("OK")){
			result = SUCCESS;
		}
		return result;
    }
    
    /**
     * 发送验证码通用方法（注册与修改密码需要用到）
     * @param telphone  手机号码
     * @return
     */
    public String sendMassage(String telphone,String codeCont){
    	    String result = FAIL;
    	  
 	    
    	    HttpClient client = new HttpClient(); 
 			PostMethod method = new PostMethod(Url); 
 				
 			//client.getParams().setContentCharset("GBK");		
 			client.getParams().setContentCharset("UTF-8");
 			method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

 			//String content = new String("您的验证码是："+codeCont+"。请不要把验证码泄露给其他人。"); 
  		    String content = new String("您的验证码是：【"+codeCont+"】，3分钟有效时间，请不要把验证码泄露给其他人。");
 			// 您的验证码是：【变量】，3分钟有效时间，请不要把验证码泄露给其他人。
  		    NameValuePair[] data = {//提交短信
  				    //new NameValuePair("account", "cf_jdhj"), 
  				    //new NameValuePair("password", "a123456"), //密码可以使用明文密码或使用32位MD5加密
  				    new NameValuePair("account", "C11714710"), 
 				    new NameValuePair("password", "85202a35086eb358e717dbf9ebc6e9bc"), //密码可以使用明文密码或使用32位MD5加密
  				    //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
  				    new NameValuePair("mobile", telphone), 
  				    new NameValuePair("content", content),
  			};
 			
 			method.setRequestBody(data);		
 			
 			
 			try {
 				client.executeMethod(method);	
 				 
 				String SubmitResult =method.getResponseBodyAsString();
 						
 				//System.out.println(SubmitResult);

 				Document doc = DocumentHelper.parseText(SubmitResult); 
 				Element root = doc.getRootElement();


 				String code = root.elementText("code");	
 				//String msg = root.elementText("msg");	
 				//String smsid = root.elementText("smsid");	
 				
 				
 				//System.out.println(code);
 				//System.out.println(msg);
 				//System.out.println(smsid);
 							
 				if("2".equals(code)){
 					result = SUCCESS;
 				}else{
 					result = FAIL;
 				}
 				
 			} catch (Exception e) {
 				e.printStackTrace();
 			}
    	
 		return result;
    }
    
    /**
     * 发送验证码通用方法（注册与修改密码需要用到）
     * @param telphone  手机号码
     * @return
     */
    public String sendMassagePayCode(String telphone,String codeCont){
    	    String result = FAIL;
    	  
    	    HttpClient client = new HttpClient(); 
 			PostMethod method = new PostMethod(Url); 
 				
 			//client.getParams().setContentCharset("GBK");		
 			client.getParams().setContentCharset("UTF-8");
 			method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

 			//String content = new String("您的验证码是："+codeCont+"。请不要把验证码泄露给其他人。"); 
  		    String content = new String("打死也不告诉其它人，"+codeCont+"您正在进行余额支付。");
 			// 您的验证码是：【变量】，3分钟有效时间，请不要把验证码泄露给其他人。
  		    NameValuePair[] data = {//提交短信
  				    //new NameValuePair("account", "cf_jdhj"), 
  				    //new NameValuePair("password", "a123456"), //密码可以使用明文密码或使用32位MD5加密
  				    new NameValuePair("account", "C11714710"), 
 				    new NameValuePair("password", "85202a35086eb358e717dbf9ebc6e9bc"), //密码可以使用明文密码或使用32位MD5加密
  				    //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
  				    new NameValuePair("mobile", telphone), 
  				    new NameValuePair("content", content),
  			};
 			
 			method.setRequestBody(data);		
 			
 			
 			try {
 				client.executeMethod(method);	
 				 
 				String SubmitResult =method.getResponseBodyAsString();
 						
 				//System.out.println(SubmitResult);

 				Document doc = DocumentHelper.parseText(SubmitResult); 
 				Element root = doc.getRootElement();


 				String code = root.elementText("code");	
 				//String msg = root.elementText("msg");	
 				//String smsid = root.elementText("smsid");	
 				
 				
 				//System.out.println(code);
 				//System.out.println(msg);
 				//System.out.println(smsid);
 							
 				if("2".equals(code)){
 					result = SUCCESS;
 				}else{
 					result = FAIL;
 				}
 				
 			} catch (Exception e) {
 				e.printStackTrace();
 			}
    	
 		return result;
    }
    
    
    /**
	    * 根据商品类型和活动类型获取商品信息
	    * @param request
	    * @param keyword 商品关键字
	    * @param categoryCode 商品类别代码
	    * @return
	    */
	   public Map<String, Object> getProductList( HttpServletRequest request, String categoryCode, String keyword){
		    Map<String, Object> dataMap = new HashMap<String, Object>();
		   
		    ProductExample example = new ProductExample();
		    example.setOrderByClause("UPDATE_TIME DESC");
			Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);// 是否有效
			if (StringHelper.isNotBlank(categoryCode)) {
				criteria.andCategoryCodeLike(categoryCode+"%");
			}
			if (StringHelper.isNotBlank(keyword)) {
				criteria.andProductNameLike("%" + keyword + "%");
			}

			this.handlePageQueryDefault(request, example);// 分页
			int count = productService.count(example);// 总条数
			List<Product> list = productService.list(example);// 数据list

			dataMap.put("total", count);
			dataMap.put("isMore", isMore(request, count));

			dataMap.put("list", ValueHelper.tranList2MapList(list,ignoreProperties));
			return dataMap;
	   }
    
    
}